import { ILogin } from "@/types/register"
import { defineStore } from "pinia"
import { useStorage } from "@vueuse/core"
import { encryptByAES, decryptByAES } from "@/utils/verification"

// 登录模块
export const loginStore = defineStore("login", () => {
  let login = useStorage("login", {
    email: "",
    password: "",
    rememberPassword: false,
  })

  /**
   * 设置在localstore中存储数据
   * @param oldLogin 要存储的数据
   */
  function setLocalLogin(oldLogin: ILogin) {

    // 加密
    login.value.email = encryptByAES(oldLogin.email);
    login.value.password = encryptByAES(oldLogin.password);
    login.value.rememberPassword = oldLogin.rememberPassword;
  }

  /**
   * 移除login
   */
  function clearLogin() {
    login.value.email = "";
    login.value.password = "";
    login.value.rememberPassword = false;
  }
  /**
   * 加密密码
   */
  function rawPassword() {
    return decryptByAES(login.value.password);
  }

  /**
   * 清除密码
   *
   */
  function removePassword() {
    login.value.password = ""
  }


  /**
   * 加密邮箱
   */
  function rawEmail() {

    return decryptByAES(login.value.email);
  }
  /**
   * 设置是否记住密码
   * @param rememberPassword 
   */
  function setRememberPassword(rememberPassword: boolean) {
    if (rememberPassword) {

      login.value.rememberPassword = rememberPassword
    } else {
      clearLogin()
    }
  }

  /**
   * 是否记住密码
   */
  function rememberPassword() {

    return login.value.rememberPassword;
  }

  return {
    login: login.value,
    setLocalLogin,
    clearLogin,
    rawPassword,
    rawEmail,
    rememberPassword,
    setRememberPassword,
    removePassword
  }

})